/**
 * 存取本地数据
 * xxLocal表示操作localStorage的方法或属性
 * xxSession表示操作sessionStorage的方法或属性
 * 所有的存储都是对象的形式，比如 userInfo: { userName: 'xx', token: 'xxx' }
 * 默认是对'userInfo'的操作，此时可以不传name参数
 */

const defaultName = "userInfo";

function UserInfo() {
    this._userInfo =
        JSON.parse(localStorage.getItem("userInfo")) ||
        JSON.parse(sessionStorage.getItem("userInfo")) ||
        {};
}
// 增 或 重置
UserInfo.prototype._addLocal = function (obj, name = defaultName) {
    localStorage.setItem(name, JSON.stringify(obj));
};

UserInfo.prototype._addSession = function (obj, name = defaultName) {
    sessionStorage.setItem(name, JSON.stringify(obj));
};

// 删
UserInfo.prototype._removeLocal = function (name = defaultName) {
    localStorage.removeItem(name);
};

UserInfo.prototype._removeSession = function (name = defaultName) {
    sessionStorage.removeItem(name);
};

// 改其中的某个字段值
UserInfo.prototype._updateLocal = function (key, value, name = defaultName) {
    const info = JSON.parse(localStorage.getItem(name));
    localStorage.setItem(
        name,
        JSON.stringify(Object.assign({}, info, { [key]: value }))
    );
};

UserInfo.prototype._updateSession = function (key, value, name = defaultName) {
    const info = JSON.parse(sessionStorage.getItem(name));
    sessionStorage.setItem(
        name,
        JSON.stringify(Object.assign({}, info, { [key]: value }))
    );
};

// 获取用户信息
UserInfo.prototype._profile = function () {
    return this._userInfo;
};

// 查
UserInfo.prototype._findLocal = function (name = defaultName) {
    return JSON.parse(localStorage.getItem(name)) || {};
};

UserInfo.prototype._findSession = function (name = defaultName) {
    return JSON.parse(sessionStorage.getItem(name)) || {};
};

const u = new UserInfo();

export const addLocal = u._addLocal;
export const addSession = u._addSession;
export const removeLocal = u._removeLocal;
export const removeSession = u._removeSession;
export const updateLocal = u._updateLocal;
export const updateSession = u._updateSession;
export const profile = u._profile();
export const findLocal = u._findLocal;
export const findSession = u._findSession;
